
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = function(root) {
  root = createTree(root);
  if(root == null)
    return [];
  if((root.left == null && root.right == null))
    return [[root.val]];
  let result = [], queue = [{
    node: root,
    depth: 0
  }];
  let tempDepth = 0;
  while(queue.length) {
    let tNode = queue[0];
    queue.splice(0, 1);
    if(tNode.node.left) queue.push({
      node: tNode.node.left,
      depth: tNode.depth + 1
    });
    if(tNode.node.right) queue.push({
      node: tNode.node.right,
      depth: tNode.depth + 1
    });
    if(result[tNode.depth]) {
      result[tNode.depth].push(tNode.node.val);
    } else {
      result[tNode.depth] = [tNode.node.val];
    }
  }
  return result.reverse();
};
let root = [3,9,20,null,null,15,7];
console.log(levelOrderBottom(root));
root = [1];
console.log(levelOrderBottom(root));
